<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Loader;
use think\Db;
use think\Request;
use think\Session;

class Order extends Base
{
    /**
     * 订单列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function OrderList()
    {
        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'order_id' => '',
                'status' => 9,
                'name' => '',
                'phone' => '',
                'username' => '',
                'begin_time' => '',
                'end_time' => '',
            ];

        }

        $this->assign('Data',$Data);
        $Where = [];
        //订单编号查询
        if($Data['order_id'] != ''){
            $Where['order_id'] = array('like','%'.$Data['order_id'].'%');

        }
        //状态查询
        if($Data['status'] != 9){
            $Where['status'] = $Data['status'];
        }

        //收件姓名查询
        if($Data['name'] != ''){
            $Where['name'] = array('like','%'.filterEmoji($Data['name']).'%');
        }

        //收件号码查询
        if($Data['phone'] != ''){
            $Where['phone'] = array('like','%'.filterEmoji($Data['phone']).'%');
        }

        //会员账号模糊查询
        if($Data['username'] != ''){

            //根据会员账号找出会员ID
            $UserWhere['username'] = array('like','%'.$Data['username'].'%');
            $UserList = Db::name('user')->where($UserWhere)->select();
            $IdArray = [];
            foreach ($UserList as $k=>$v){
                $IdArray[] = $UserList[$k]['id'];
            }
            $Where['user_id'] = array('in',$IdArray);
        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

        //总记录条数
        $Count = OrderCount($Where);
        $this->assign('Count', $Count);

        //订单信息
        $OrderList = OrderList($Where);
        $this->assign('OrderList', $OrderList['OrderList']);

        //分页
        $this->assign('Page', $OrderList['Page']);

        return $this->fetch('OrderList');
    }

    /**
     * 订单详情
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function OrderEdit(){
        //订单信息
        $OrderInfo = OrderInfo(['id'=>Param('id')]);
        $this->assign('OrderInfo',$OrderInfo);

        //订单信息
        // $GoodsInfo = GoodsInfo(['id'=>$OrderInfo['goods_id']]);
        $goods_id = explode(',', $OrderInfo['goods_id']);
        $num = explode(',', $OrderInfo['num']);
        foreach ($goods_id as $k=>$v) {
            $GoodsInfo = GoodsInfo(['id'=>$v]);
            $GoodsInfo['num'] = $num[$k];
            $infos[] = $GoodsInfo;
        }
        // echo "<pre>";
        // var_dump($infos);die;
        $this->assign('GoodsInfo',$infos);

        //会员信息
        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
        $this->assign('UserInfo',$UserInfo);

        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();
            if(!empty($Data['recommend'])){
                $RecommendInfo = UserInfo(['username'=>$Data['recommend']]);
                if(empty($RecommendInfo)){
                    return ['status'=>0,'message'=>'推荐账号不存在'];
                }
            }
            //向表中添加数据
            if(Db::name('user')->update($Data)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

        return $this->fetch('OrderEdit');
    }

    /**
     * 订单删除
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function OrderDelete(){
        //Post请求操作
        if(IsPost()){
            if(Db::name('user_order')->where(['id'=>Param('id')])->delete()){
                return ['status'=>1,'message'=>'删除成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
    }


    /**
     * 订单物流
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function OrderSend(){
        //订单信息
        $OrderInfo = OrderInfo(['id'=>Param('id')]);
        $this->assign('OrderInfo',$OrderInfo);
        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();

            //更改订单状态
            $Data['status'] = 2;

            //修改表中数据
            if(Db::name('user_order')->update($Data)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }
        return $this->fetch('OrderSend');
    }

    /**
     * 订单表导出
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function OrderExport(){

        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'order_id' => '',
                'status' => 9,
                'name' => '',
                'phone' => '',
                'username' => '',
                'begin_time' => '',
                'end_time' => '',
            ];

        }
        $Where = [];

        //订单编号查询
        if($Data['order_id'] != ''){
            $Where['order_id'] = array('like','%'.$Data['order_id'].'%');

        }
        //状态查询
        if($Data['status'] != 9){
            $Where['status'] = $Data['status'];
        }

        //收件姓名查询
        if($Data['name'] != ''){
            $Where['name'] = array('like','%'.$Data['name'].'%');
        }

        //收件号码查询
        if($Data['phone'] != ''){
            $Where['phone'] = array('like','%'.$Data['phone'].'%');
        }

        //会员账号模糊查询
        if($Data['username'] != ''){

            //根据会员账号找出会员ID
            $UserWhere['username'] = array('like','%'.$Data['username'].'%');
            $UserList = Db::name('user')->where($UserWhere)->select();
            $IdArray = [];
            foreach ($UserList as $k=>$v){
                $IdArray[] = $UserList[$k]['id'];
            }
            $Where['user_id'] = array('in',$IdArray);
        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

        $xlsData = Db('user_order')->where($Where)->select();

// var_dump($xlsData);die;
        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.Worksheet.Drawing');
        Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E,F,G,H,I,J,K,L,M");
        $arrHeader = array('订单号','会员信息','商品信息 ','支付金额','支付方式','收货地址','收货姓名','联系电话','下单时间','订单备注','订单状态','快递名称','快递单号');

        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };

// echo "<pre>";
// var_dump($xlsData);die;
        //填充表格信息
        foreach($xlsData as $k=>$v){
            $UserInfo = UserInfo(['id'=>$v['user_id']]);
            // $GoodsInfo = GoodsInfo(['id'=>$v['goods_id']]);
            $goods = explode(',', $v['goods_id']);
            $nums = explode(',', $v['num']);
            foreach ($goods as $key => $value) {
                $GoodsInfo = GoodsInfo(['id'=>$value]);
                $v['allnames'][] = $GoodsInfo['name'].'X'.$nums[$key];
                //获取所有商品名称
                $names = implode(',',$v['allnames']);
            }
            if($v['pay_type']){
                $v['pay_type'] = '已支付';
            }else{
                $v['pay_type'] = '未支付';
            }

            if($v['status'] == 0){
                $v['status'] = '待付款';
            }elseif($v['status'] == 1){
                $v['status'] = '待发货';
            }elseif($v['status'] == 2){
                $v['status'] = '待收货';
            }elseif($v['status'] == 3){
                $v['status'] = '已完成';
            }

            $k +=2;
            $objActSheet->setCellValue('A'.$k,$v['order_id']." ");
            $objActSheet->setCellValue('B'.$k, $UserInfo['username']);
            $objActSheet->setCellValue('C'.$k, $names);
            $objActSheet->setCellValue('D'.$k, $v['pay_amount']);
            $objActSheet->setCellValue('E'.$k, $v['pay_type']);
            $objActSheet->setCellValue('F'.$k, $v['address']);
            $objActSheet->setCellValue('G'.$k, $v['name']);
            $objActSheet->setCellValue('H'.$k, $v['phone']);
            $objActSheet->setCellValue('I'.$k,  date('Y-m-d H:i',$v['add_time']));
            $objActSheet->setCellValue('J'.$k, $v['remarks']);
            $objActSheet->setCellValue('K'.$k, $v['status']);
            $objActSheet->setCellValue('L'.$k, $v['express_name']);
            $objActSheet->setCellValue('M'.$k, $v['express_num']);
            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);

            $width = array(10,15,20,25,30);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[2]);
            $objActSheet->getColumnDimension('B')->setWidth($width[2]);
            $objActSheet->getColumnDimension('C')->setWidth($width[3]);
            $objActSheet->getColumnDimension('D')->setWidth($width[2]);
            $objActSheet->getColumnDimension('E')->setWidth($width[1]);
            $objActSheet->getColumnDimension('F')->setWidth($width[2]);
            $objActSheet->getColumnDimension('G')->setWidth($width[1]);
            $objActSheet->getColumnDimension('H')->setWidth($width[2]);
            $objActSheet->getColumnDimension('I')->setWidth($width[1]);
            $objActSheet->getColumnDimension('J')->setWidth($width[1]);
            $objActSheet->getColumnDimension('K')->setWidth($width[1]);
            $objActSheet->getColumnDimension('L')->setWidth($width[1]);
            $objActSheet->getColumnDimension('M')->setWidth($width[1]);
        }
// var_dump($names);die;

        $outfile = "订单信息列表.xlsx";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output');
    }


    //订单导入
    public function OrderExport_1(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
var_dump($file);die;
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>1567800000,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'xlsx');

        if($info){
            //返回上传图片路径
            $path = "/xlsx/".$info->getSaveName();
        }else{
            // 上传失败获取错误信息
            return ['status'=>0,'message'=>$file->getError()];
        }
        // require_once dirname(__FILE__) . '/Lib/Classes/PHPExcel/IOFactory.php';  
      Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.Worksheet.Drawing');
        // Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $PHPReader = new \PHPExcel_Reader_Excel2007();
    //加载excel文件  
    $filename = ROOT_PATH.'/public'.$path;  
    // var_dump($filename);
    // $objPHPExcelReader = PHPExcel_IOFactory::load($filename);    
  $PHPExcel = $PHPReader->load($filename); //加载excel对象
//   var_dump($PHPExcel);die;
    // $sheet = $objPHPExcelReader->getSheet(0);        // 读取第一个工作表(编号从 0 开始)  
    // $highestRow = $sheet->getHighestRow();           // 取得总行数  
    // $highestColumn = $sheet->getHighestColumn();     // 取得总列数  
  $sheet = $PHPExcel->getSheet(0); //获取指定的sheet表
        $rows = $sheet->getHighestRow();//行数
        $cols = $sheet->getHighestColumn();//列数
    $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');  
    // 一次读取一列  
    $res_arr = array();  
    for ($row = 2; $row <= $rows; $row++) {  
        $row_arr = array();  
        for ($column = 0; $arr[$column] <= $cols; $column++) {  
            $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();  
            if(is_object($val))  $val= $val->__toString();
            $row_arr[] = $val;  
        }  
        $res_arr[] = $row_arr;  
    }  
    // $data = array();
    //     for ($i = 2; $i <= $rows; $i++){ //行数是以第1行开始
    //         $count = 0;
    //         for ($j = 'A'; $j <= $cols; $j++) { //列数是以A列开始
    //             $value = $sheet->getCell($j . $i)->getValue();
    //             if ($value) {
    //                 $data[$i - 1][$count] = (string)$sheet->getCell($j . $i)->getValue();
    //                 $count += 1;
    //             }
    //         }
    //     }
        echo '<pre>';
        var_dump($data);die;;
    
    $in = array();
    $ins = array();
    foreach ($res_arr as $v){
        $in['provider'] = $v[1];
        $in['carnum'] = $v[2];
        $in['outnum'] = $v[3];
        $in['cartype'] = $v[4];
        $in['carattr'] = $v[5];
        // if($v[6] == NULL){
        //     $in['jiaotime'] = '';
        // }else{
        //     if(is_float($v[6])){
        //         $in['jiaotime'] = gmdate('Y-m-d',intval(($v[6]-25569)*3600*24));
        //     }else{
        //         return ["status"=>0,"message"=>'第'.$v[0]."行交车时间有问题"];
        //     }
            
        // }
        if(is_float($v[6])){
            $in['jiaotime'] = gmdate('Y-m-d',intval(($v[6]-25569)*3600*24));
        }else{
            $in['jiaotime'] = $v['6'];
        }
        // var_dump($v['6']);die;
        // $in['jiaotime'] = gmdate('Y-m-d',intval(($v[6]-25569)*3600*24));
        // $in['tuitime'] = gmdate('Y-m-d',intval(($v[7]-25569)*3600*24));
        // if($v[7] == NULL){
        //     $in['tuitime'] = '';
        // }else{
        //     if(is_float($v[7])){
        //         $in['tuitime'] = gmdate('Y-m-d',intval(($v[7]-25569)*3600*24));
        //     }else{
        //         return ["status"=>0,"message"=>'第'.$v[0]."行退车时间有问题"];
        //     }
            
        // }
        if(is_float($v[7])){
            $in['tuitime'] = gmdate('Y-m-d',intval(($v[7]-25569)*3600*24));
        }else{
            $in['tuitime'] = $v['7'];
        }
        $in['cusname'] = $v[8];
        $in['stopplace'] = $v[9];
        // $in['qtime'] = gmdate('Y-m-d',intval(($v[10]-25569)*3600*24));
        // if($v[10] == NULL){
        //     $in['qtime'] = '';
        // }else{
        //     if(is_float($v[10])){
        //         $in['qtime'] = gmdate('Y-m-d',intval(($v[10]-25569)*3600*24));
        //     }else{
        //         return ["status"=>0,"message"=>'第'.$v[0]."行交强险截止日期有问题"];
        //     }
            
        // }
        if(is_float($v[10])){
            $in['qtime'] = gmdate('Y-m-d',intval(($v[10]-25569)*3600*24));
        }else{
            $in['qtime'] = $v['10'];
        }
        // $in['qtime'] = $v[10];
        $in['inscompany'] = $v[11];
        // $in['stime'] = gmdate('Y-m-d',intval(($v[12]-25569)*3600*24));
        // if($v[12] == NULL){
        //     $in['stime'] = '';
        // }else{
        //     if(is_float($v[12])){
        //          $in['stime'] = gmdate('Y-m-d',intval(($v[12]-25569)*3600*24));
        //     }else{
        //         return ["status"=>0,"message"=>'第'.$v[0]."行商业险截止日期有问题"];
        //     }
           
        // }
        if(is_float($v[12])){
            $in['stime'] = gmdate('Y-m-d',intval(($v[12]-25569)*3600*24));
        }else{
            $in['stime'] = $v['12'];
        }
        // $in['stime'] = $v[12];
        $in['inscompany1'] = $v[13];
        $in['beizhu'] = $v[14];
        $ins[] = $in;
    }
    // echo '<pre>';
    // var_dump($ins);die;
    $pd = Db::name('carinfo')->insertAll($ins);
        if($pd){ //修改数据
            return ["status"=>1,"message"=>"导入成功"];
        }else{
            return ["status"=>0,"message"=>"导入失败"];
        }
    }
}